﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace Base.ModuleBase.Infrasttuctures
{
    public sealed class TaskPool
    {
        private Queue<Task> _taskQueue=new Queue<Task>();
        private int _maxRunningTask ;
        private List<Task> _runningTasks=new List<Task>();
        private Dispatcher _dispatcher;
        public TaskPool():this(Environment.ProcessorCount)
        {
        }

        public TaskPool(int maxRunningTask)
        {
            _maxRunningTask = maxRunningTask;
            _dispatcher = Application.Current.Dispatcher;
        }

        public void AddTask(Task task)
        {
            lock (_runningTasks)
            {
                _taskQueue.Enqueue(task);
            }
        }

        public void StartAll()
        {

            for (int i = 0; i < _maxRunningTask + 1; i++)
            {
                StartTask();
            }
        }

        private void OnTaskEnd(Task task)
        {
            lock (_runningTasks)
            {
                _runningTasks.Remove(task);
            }
            StartTask();
        }

        private void StartTask()
        {
            lock (_runningTasks)
            {
                if (_taskQueue.Count == 0 || _maxRunningTask <= _runningTasks.Count) return;
                var task = _taskQueue.Dequeue();
                task.ContinueWith(OnTaskEnd);
                task.Start();
                _runningTasks.Add(task);
            }
        }
    }
}
